package com.bml.architect.netty.heart;

import com.bml.architect.netty.base.NettyClientHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.util.Random;

public class HeartNettyClient {


    public static void main(String[] args) {

        EventLoopGroup clientGoup = new NioEventLoopGroup();

        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(clientGoup)
                    .channel(NioSocketChannel.class)// 使用 NioSocketChannel 作为客户端的通道实现
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new StringDecoder());
                            ch.pipeline().addLast(new StringEncoder());
                            ch.pipeline().addLast(new HeartNettyClientHandler());
                        }
                    });

            //启动客户端去连接服务器端
            ChannelFuture cf = bootstrap.connect("127.0.0.1", 8000).sync();
            Channel channel = cf.channel();
            String text = "heart Packet";
            while (channel.isActive()){
              Thread.sleep(4000);
              channel.writeAndFlush(text);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            clientGoup.shutdownGracefully();
        }
    }


}